<template>
    <div class="home">
        <div class="left">
            <div class="data">
                <div class="title">
                    <div class="label">数据概述</div>
                    <!-- <el-radio v-model="radio" label="1">本周</el-radio>
                    <el-radio v-model="radio" label="2">本月</el-radio>
                    <el-radio v-model="radio" label="3">本年</el-radio> -->
                </div>
                <div class="detail">
                    <div class="item">
                        <div class="text">本月累计营收：</div>
                        <div class="value">￥{{ nowMonthRevenue }}
                            <!-- <span>
                                <i class="el-icon-caret-top"></i>
                                同比上月12%
                            </span> -->
                        </div>
                    </div>
                    <div class="item">
                        <div class="text">本月累计订单：</div>
                        <div class="value">{{ nowMonthOrderCount }}
                            <!-- <span>
                                <i class="el-icon-caret-top"></i>
                                同比上月26%
                            </span> -->
                        </div>
                    </div>
                    <div class="item">
                        <div class="text">本月累计用户：</div>
                        <div class="value">{{ nowMonthUsersCount }}
                            <!-- <span>
                                <i class="el-icon-caret-bottom"></i>
                                同比上月8%
                            </span> -->
                        </div>
                    </div>
                </div>
            </div>
            <div class="methods">
                <div class="title">
                    <div class="label">常用功能</div>
                </div>
                <div class="items">
                    <div class="item" @click="handleEdit('0')">
                        <img src="@/assets/img/add.png" alt="">
                        <div class="text">新增菜品</div>
                    </div>
                    <div class="item" @click="handleEdit('1')">
                        <img src="@/assets/img/kucun.png" alt="">
                        <div class="text">新增库存</div>
                    </div>
                    <div class="item" @click="handleEdit('2')">
                        <img src="@/assets/img/dingdan.png" alt="">
                        <div class="text">订单查询</div>
                    </div>
                    <div class="item" @click="handleEdit('3')">
                        <img src="@/assets/img/xitong.png" alt="">
                        <div class="text">更改信息</div>
                    </div>
                    <!-- <div class="item">
                        <i class="el-icon-delete"></i>
                        <div class="text">新增商品</div>
                    </div> -->
                </div>
            </div>
            <div class="priceTitle">
                <span>
                    营业额
                    <!-- <el-button @click="test">test</el-button> -->
                </span>
                <el-date-picker @change="handleChange" :picker-options="{ 'firstDayOfWeek': 1 }" v-model="dateWeek"
                    type="week" format="yyyy 第 WW 周" placeholder="选择周">
                </el-date-picker>
            </div>
            <div class="priceData" ref="priceDataRef">
            </div>

        </div>
        <div class="right">
            <div class="category" ref="categoryRef"></div>
            <div class="food" ref="foodRef"></div>

        </div>
        <!-- <div class="text" ref="textRef"></div> -->
    </div>
</template>

<script>
import * as echarts from 'echarts';
import { getHomeInfo } from "@/api/foodManage"
export default {

    data() {
        return {
            radio: '1',
            dateWeek: '',
            monday: '',
            sunday: '',
            nowMonthRevenue: '',
            nowMonthOrderCount: '',
            nowMonthUsersCount: '',
            countArr: [],
            weekList: [],
            areaList: [
                {
                    label: '昆明',
                    value: 'kunming'
                }, {
                    label: '曲靖',
                    value: 'qujing'
                }, {
                    label: '玉溪',
                    value: 'yuxi'
                }, {
                    label: '昭通',
                    value: 'zhaotong'
                }, {
                    label: '保山',
                    value: 'baoshan'
                }, {
                    label: '普洱',
                    value: 'puer'
                }, {
                    label: '临沧',
                    value: '临沧'
                }, {
                    label: '西双版纳',
                    value: 'xsbn'
                }, {
                    label: '大理自治州',
                    value: 'dali'
                }

            ],
            areaListLabel: [
                {
                    label: '昆明',
                }, {
                    label: '曲靖',
                }, {
                    label: '玉溪',
                }, {
                    label: '昭通',
                }, {
                    label: '保山',
                }, {
                    label: '普洱',
                }, {
                    label: '临沧',
                }, {
                    label: '西双版纳',
                }, {
                    label: '大理自治州',
                }
            ],
            areaData: [],
            foodData: []
        };
    },
    created() {
        function getCurrentWeekDates() {
            const today = new Date();  // 获取当前日期
            const dayOfWeek = today.getDay();  // 获取当前星期几 (0 表示周日)

            // 计算周一日期
            const mondayDate = new Date(today);
            mondayDate.setDate(today.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));

            // 计算周日日期
            const sundayDate = new Date(mondayDate);
            sundayDate.setDate(mondayDate.getDate() + 6);

            // 格式化日期 "YYYY-MM-DD"
            const formatDate = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };

            return {
                monday: formatDate(mondayDate),
                sunday: formatDate(sundayDate),
            };
        }

        const weekDates = getCurrentWeekDates();
        console.log(weekDates, 'sd');

        this.monday = weekDates.monday;
        this.sunday = weekDates.sunday;
        console.log(this.monday, this.sunday, 'sd');


        if (true) {
            function getCurrentWeekDates() {
                const today = new Date();
                const dayOfWeek = today.getDay();  // 获取星期几，0 表示周日
                const diffToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;  // 计算与周一的差距

                const mondayDate = new Date(today);
                mondayDate.setDate(today.getDate() - diffToMonday);  // 计算周一日期

                const weekDates = [];

                for (let i = 0; i < 7; i++) {
                    const date = new Date(mondayDate);
                    date.setDate(mondayDate.getDate() + i);
                    const formattedDate = formatDate(date);
                    weekDates.push(formattedDate);
                }

                return weekDates;
            }

            function formatDate(date) {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            }

            const currentWeekDates = getCurrentWeekDates();
            console.log("当前周的日期数组：", currentWeekDates);
            this.weekList = currentWeekDates;

        }

        this.getHomeInfo()
    },
    mounted() {

    },

    methods: {
        handleChange(val) {
            this.getHomeInfo()
        },
        setEchart() {
            let myChart = echarts.init(this.$refs.priceDataRef);

            var data_val = this.weekList,
                xAxis_val = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            var data_val1 = [0, 0, 0, 0, 0, 0, 0];
            var option = {
                grid: {
                    left: 10,
                    top: '10%',
                    bottom: 20,
                    right: 40,
                    containLabel: true,
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
                        shadowStyle: {
                            // color: "#7083db",
                            color: "rgba(255, 255, 255, 0.26)"
                        },
                        // label: {
                        //     show: true,
                        //     formatter: function (params) {
                        //         return params.seriesData[0].value
                        //         // 假设此轴的 type 为 'time'。
                        //     },
                        //     margin: -470,
                        //     backgroundColor: '#7083db',
                        //     borderWidth:200,
                        //     color:'#fff'
                        // },
                    },

                },
                xAxis: {
                    data: xAxis_val,
                    boundaryGap: false,
                    axisLine: {
                        show: false,
                    },
                    axisTick: {
                        show: false,
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#ccc',
                        },
                    },
                },
                yAxis: {
                    ayisLine: {
                        show: false,
                    },
                    // x轴刻度线文字颜色
                    axisLabel: {
                        textStyle: {
                            color: '#5c6076',
                        },
                    },
                    // x轴线
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#fff',
                        },
                    },
                    // Y轴
                    axisLine: {
                        lineStyle: {
                            color: '#fff',
                        },
                    },
                },
                series: [
                    {
                        type: 'line',
                        name: '营业额',
                        smooth: true,
                        symbolSize: 10,
                        animation: false,
                        lineWidth: 1.2,
                        hoverAnimation: false,
                        data: data_val,
                        symbol: 'circle',
                        itemStyle: {
                            normal: {
                                color: '#7083db',
                            },
                        },
                        lineStyle: {
                            normal: {
                                width: 5,
                                shadowBlur: 5,
                                shadowColor: '#7083db',
                                shadowOffsetY: 8
                            }
                        },
                        // 瀑布
                        areaStyle: {
                            normal: {
                                color: '#7083db',
                                opacity: 0.16,
                            },
                        },
                    },
                ],
            };
            myChart.setOption(option);


            let categoryChart = echarts.init(this.$refs.categoryRef);
            let categoryOption = {
                title: {
                    text: "地区分布",
                    x: "center",
                },
                tooltip: {
                    trigger: "item",
                    formatter: "{a} <br/>{b} : {c} ({d}%)",
                },
                // legend: {
                //     orient: "vertical",
                //     left: "left",
                //     data: this.areaListLabel,
                // },
                series: [
                    {
                        name: "地区来源",
                        type: "pie",
                        radius: "55%",
                        center: ["50%", "60%"],
                        data: this.areaData,
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: "rgba(0, 0, 0, 0.5)",
                            },
                        },
                    },
                ],
            };
            categoryChart.setOption(categoryOption);

            let foodChart = echarts.init(this.$refs.foodRef);
            let foodOption = {
                title: {
                    text: "菜品分布",
                    x: "center",
                },
                tooltip: {
                    trigger: "item",
                    formatter: "{a} <br/>{b} : {c} ({d}%)",
                },
                // legend: {
                //     orient: "vertical",
                //     left: "left",
                //     data: ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"],
                // },
                series: [
                    {
                        name: "菜品数量",
                        type: "pie",
                        radius: "55%",
                        center: ["50%", "60%"],
                        data: this.foodData,
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: "rgba(0, 0, 0, 0.5)",
                            },
                        },
                    },
                ],
            };
            foodChart.setOption(foodOption);
        },
        async getHomeInfo() {
            if (this.dateWeek) {
                const currentDate = new Date(this.dateWeek);  // 输入的日期对象
                const day = currentDate.getDay();    // 获取当前星期几 (0表示星期日)
                const diffToMonday = day === 0 ? 6 : day - 1;  // 计算与周一的差距
                const monday = new Date(currentDate);
                monday.setDate(currentDate.getDate() - diffToMonday);  // 设置为周一日期

                const sunday = new Date(monday);
                sunday.setDate(monday.getDate() + 6);  // 设置为周日日期

                // 格式化输出 "YYYY-MM-DD"
                const formatDate = (d) => {
                    const year = d.getFullYear();
                    const month = String(d.getMonth() + 1).padStart(2, '0');
                    const day = String(d.getDate()).padStart(2, '0');
                    return `${year}-${month}-${day}`;
                };

                let dateInfo = {
                    monday: formatDate(monday),
                    sunday: formatDate(sunday)
                };
                this.monday = dateInfo.monday;
                this.sunday = dateInfo.sunday;
            }


            let data = {
                startTime: this.monday + "T00:00:00",
                endTime: this.sunday + "T23:59:59",
            }
            console.log(data, 'dddd');

            const res = await getHomeInfo(data);
            if (res.code == 200) {
                console.log(res, 'rr');

                this.nowMonthRevenue = res.data.dataOverviewMap.nowMonthRevenue
                this.nowMonthOrderCount = res.data.dataOverviewMap.nowMonthOrderCount
                this.nowMonthUsersCount = res.data.dataOverviewMap.nowMonthUsersCount
                if (true) {
                    function getCurrentWeekDates() {
                        const today = new Date();
                        const dayOfWeek = today.getDay();  // 获取星期几，0 表示周日
                        const diffToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;  // 计算与周一的差距

                        const mondayDate = new Date(today);
                        mondayDate.setDate(today.getDate() - diffToMonday);  // 计算周一日期

                        const weekDates = [];

                        for (let i = 0; i < 7; i++) {
                            const date = new Date(mondayDate);
                            date.setDate(mondayDate.getDate() + i);
                            const formattedDate = formatDate(date);
                            weekDates.push({
                                date: formattedDate,
                                total: 0
                            });
                        }

                        return weekDates;
                    }

                    function formatDate(date) {
                        const year = date.getFullYear();
                        const month = String(date.getMonth() + 1).padStart(2, '0');
                        const day = String(date.getDate()).padStart(2, '0');
                        return `${year}-${month}-${day}`;
                    }

                    const currentWeekDates = getCurrentWeekDates();
                    console.log("当前周的日期数组：", currentWeekDates);
                    this.weekList = currentWeekDates;

                }
                for (let i = 0; i < this.weekList.length; i++) {
                    let found = false;  // 标记是否找到匹配项
                    for (let j = 0; j < res.data.nextWeekRevenue.length; j++) {
                        if (this.weekList[i].date === res.data.nextWeekRevenue[j].date) {
                            this.weekList[i].total = res.data.nextWeekRevenue[j].total;
                            found = true;  // 标记为已找到
                            break;  // 跳出内层循环
                        }
                    }
                    if (!found) {
                        this.weekList[i].total = 0;
                    }
                }
                this.weekList = this.weekList.map(item => item.total)

                this.areaData = res.data.areaCategory.map(item => {
                    return {
                        name: item.name,
                        value: item.total
                    }
                })
                console.log(this.areaData, 'areaData');
                this.areaData.forEach(item => {
                    this.areaList.forEach(_item => {
                        if (item.name == _item.value) {
                            item.name = _item.label
                        }
                    })
                })
                this.foodData = res.data.dishCategory.map(item => {
                    return {
                        name: item.name,
                        value: item.total
                    }
                })
                this.setEchart()

            }
        },
        handleEdit(flag) {
            if (flag == 0) {
                this.$router.push({
                    path: '/foodManage'
                })
            } else if (flag == 1) {
                this.$router.push({
                    path: '/inventoryManage'
                })
            } else if (flag == 2) {
                this.$router.push({
                    path: '/orderManage'
                })
            } else if (flag == 3) {
                this.$router.push({
                    path: '/merchantInfo'
                })
            }
        }
    },
};
</script>
<style lang="less" scoped>
.home {
    height: 100%;
    background-color: #f3f4fb;
    display: flex;

    .text {
        // height: 500px;
    }

    .left {
        width: 60%;
        display: flex;
        flex-direction: column;

        .data {
            .title {
                display: flex;
                align-items: center;
                font-weight: 700;

                .label {
                    margin-right: auto;
                }
            }

            padding: 15px;
            height: 120px;
            background-color: #fff;
            border-radius: 15px;

            .detail {
                display: flex;
                margin-top: 15px;
                justify-content: space-between;

                .item {
                    .text {
                        font-size: 16px;
                    }

                    .value {
                        font-weight: 700;
                        font-size: 22px;

                        span {
                            font-size: 14px;
                            color: #999;

                            .el-icon-caret-top {
                                color: red;
                            }

                            .el-icon-caret-bottom {
                                color: green;
                            }
                        }
                    }


                }

            }
        }

        .methods {
            margin-top: 20px;

            .title {
                display: flex;
                align-items: center;
                font-weight: 700;

                .label {
                    margin-right: auto;
                }
            }

            padding: 15px;
            height: 140px;
            background-color: #fff;
            border-radius: 15px;

            .items {
                display: flex;
                justify-content: space-between;

                .item {
                    cursor: pointer;

                    img {
                        width: 60px;
                        height: 60px;
                    }

                    i {
                        font-size: 60px;
                        color: #155bd4;
                    }


                }
            }
        }

        .priceTitle {
            font-weight: 700;
            padding-left: 15px;
            display: flex;
            align-items: center;
            margin-top: 20px;
            height: 40px;
            background-color: #fff;
            border-top-left-radius: 15px;
            border-top-right-radius: 15px;

            span {
                margin-right: 50px;
            }
        }

        .priceData {
            padding: 15px;
            height: 140px;
            background-color: #fff;
            border-bottom-left-radius: 15px;
            border-bottom-right-radius: 15px;
            flex: 1
        }
    }

    .right {
        width: 40%;
        margin-left: 10px;

        .category {
            height: 50%;
            background-color: #fff;
            border-radius: 15px;

        }

        .food {
            margin-top: 15px;
            height: 50%;
            background-color: #fff;
            border-radius: 15px;

        }
    }
}
</style>